﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class CustomControls_Lavanderia : System.Web.UI.UserControl
{
    public List<BLLLaundry.Full_Detail> details
    {
        get { return (List<BLLLaundry.Full_Detail>)Session["detail"]; }
        set { Session["detail"] = value; }
    }
    protected int Id
    {
        get
        {
            if (ViewState["id"] == null) return 0;
            return (int)ViewState["id"];
        }
        set { ViewState["id"] = value; }
    }
    protected String[] Message
    {
        get
        {
            if (Session["Message"] == null)
            {
                String[] m = {"",""};
                return m;
            }
            return (String[])Session["Message"];
        }
        set { Session["Message"] = value; }
    }
    private bool Add
    {
        get
        {
            if (ViewState["add"] != null)
            {
                return (bool)ViewState["add"];
            }
            else
            {
                return false;
            }
        }
        set
        {
            ViewState["add"] = value;
        }
    }
    private bool Edit
    {
        get
        {
            if (ViewState["Edit"] != null)
            {
                return (bool)ViewState["Edit"];
            }
            else
            {
                return false;
            }
        }
        set
        {
            ViewState["Edit"] = value;
        }
    }
    private bool View
    {
        get
        {
            if (ViewState["View"] != null)
            {
                return (bool)ViewState["View"];
            }
            else
            {
                return false;
            }
        }
        set
        {
            ViewState["View"] = value;
        }
    }
    private bool Disable
    {
        get
        {
            if (ViewState["Disable"] != null)
            {
                return (bool)ViewState["Disable"];
            }
            else
            {
                return false;
            }
        }
        set
        {
            ViewState["Disable"] = value;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            chkDecrease.Checked = true;
            txtDate.Text = DateTime.Now.ToShortDateString();
            String[] msg = { "", "" };
            Message = msg;
            List<BLLLaundry.Full_Detail> list = new List<BLLLaundry.Full_Detail>();
            btnPrint.Visible = false;
            if (!String.IsNullOrEmpty(Request.QueryString["id"]) && Request.Url.ToString().Contains("Editar.aspx"))
            {
                int cid = 0;
                int.TryParse(Request.QueryString["id"], out cid);
                this.Id = cid;
                BLLLaundry bll = new BLLLaundry();
                ReceivedNote n = bll.GetReceivedNoteById(this.Id);
                list = bll.GetReceivedNoteDetail(this.Id);
                this.btnSave.Visible = false;
                imgAdd.Visible = false;
                if (n.Id > 0)
                {
                    populateInfo(n);
                    btnPrint.Visible = true;
                    
                }
                else
                {
                    String[] error = { Resources.Resource.ERROR, Resources.Resource.RECEIVED_NOTE_NOT_FOUND };
                    Message = error;
                    this.Response.Redirect("Default.aspx?recover=y");
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(Request.QueryString["id"]))
                {
                    String[] error = { Resources.Resource.ERROR, Resources.Resource.INVALID_URL };
                    Message = error;
                    this.Response.Redirect("Default.aspx?recover=y");
                }
            }
            BLLProcess DB = new BLLProcess();
            List<Process> processes = DB.GetProcesses();
            int total = 11 - list.Count;
            if (list.Count > 10)
                total = 2;
            for (int i = 1; i < total; i++)
            {
                BLLLaundry.Full_Detail d = new BLLLaundry.Full_Detail();
                d.Id = i * -1;
                d.Processes = processes;
                list.Add(d);
            }
            details = list;
            bindGrid();
            //SetupPageByUserRoles();
        }
        ((Literal)Page.Master.FindControl("ltrShowMessage")).Text = "0";
    }
    private void bindGrid()
    {
        grid.DataSource = details;
        grid.DataBind();
    }
    private void populateInfo(ReceivedNote r)
    {
        txtName.Text = r.Client.Name;
        txtDocumentId.Text = r.Client.DocumentId;
        txtAddress.Text = r.Client.Address;
        txtPhone.Text = r.Client.Phone;
        txtNote.Text = r.Note;
        txtDate.Text = r.Date.ToShortDateString();
        ltrCode.Text = r.txtCode;
        txtName.ReadOnly = true;
        txtDocumentId.ReadOnly = true;
        txtAddress.ReadOnly = true;
        txtPhone.ReadOnly = true;
        txtNote.ReadOnly = true;
        txtDate.ReadOnly = true;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        buildDetails();
        int total = (from d in details where d.Id >= 0 select d).Count();
        if (total > 0)
        {
            ReceivedNote r = new ReceivedNote();
            Client c = new Client();
            r.Client = c;
            r.Client.Name = txtName.Text.Trim();
            r.Client.DocumentId = txtDocumentId.Text.Trim();
            r.Client.Address = txtAddress.Text.Trim();
            r.Client.Phone = txtPhone.Text.Trim();
            r.Client.CreatedBy = Util.GetCurrentUserId();
            r.Client.CreatedDate = DateTime.Now;
            r.Note = txtNote.Text;
            r.Date = Convert.ToDateTime(txtDate.Text.Trim());
            if (this.Id == 0)
            {
                r.CreatedBy = Util.GetCurrentUserId();
                r.CreatedDate = DateTime.Now;
            }
            else
            {
                r.Id = this.Id;
            }

            BLLLaundry bll = new BLLLaundry();
            long RNId = 0;
            if (bll.SaveReceivedNote(r, details, chkDecrease.Checked, out RNId))
            {
                String[] error = { Resources.Resource.SUCCESS, Resources.Resource.RECEIVED_NOTE_SAVED };
                Message = error;
                this.Response.Redirect("Editar.aspx?id=" + RNId);
            }
            else
            {

                ((Literal)Page.Master.FindControl("ltrShowMessage")).Text = "1";
                ((Literal)Page.Master.FindControl("ltrMessage")).Text = Resources.Resource.UPDATE_ERROR;
                ((Literal)Page.Master.FindControl("ltrMessageType")).Text = Resources.Resource.ERROR;

            }
        }
        else
        {
            lblMessage.Text = "Debe seleccionar al menos un detalle";  
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        this.Response.Redirect("Default.aspx?recover=y");
    }
    protected void SetupPageByUserRoles()
    {
        List<SessionPermissions> userPermissions = new List<SessionPermissions>();
        userPermissions = (List<SessionPermissions>)Session[GlobalNames.UserPermissions];
        userPermissions = (from upb in userPermissions
                           where upb.ModuleId == (long)GlobalEnums.Modules.Usuarios
                           select upb).ToList();
        if (userPermissions.Count() > 0)
        {
            foreach (SessionPermissions up in userPermissions)
            {
                if (up.PermissionId == (long)GlobalEnums.Permissions.Agregar)
                    Add = true;
                if (up.PermissionId == (long)GlobalEnums.Permissions.Editar)
                    Edit = true;
                if (up.PermissionId == (long)GlobalEnums.Permissions.Ver)
                    this.View = true;
                if (up.PermissionId == (long)GlobalEnums.Permissions.Habilitar_Deshabilitar)
                    this.Disable = true;
            }
            if (!View)
                this.Response.Redirect("~/Default.aspx");
            if (!Add && Id == 0)
            {
                this.Response.Redirect("Default.aspx");
            }
            if (Id > 0 && !Edit)
                btnSave.Visible = false;

        }
        else
        {
            this.Response.Redirect("~/Default.aspx");
        }
    }
    protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                BLLLaundry.Full_Detail detail = (BLLLaundry.Full_Detail)e.Row.DataItem;
                DropDownList drd = (DropDownList)e.Row.FindControl("drdProcess");
                TextBox txtQuantity = (TextBox)e.Row.FindControl("txtQuantity");
                TextBox txtPrice = (TextBox)e.Row.FindControl("txtPrice");
                HiddenField hdnId = (HiddenField)e.Row.FindControl("hdnId");
                drd.Items.Clear();
                drd.Items.Add(new ListItem("", ""));
                foreach (Process p in detail.Processes)
                {
                    drd.Items.Add(new ListItem(p.Name, p.Id.ToString()));
                }
                drd.SelectedValue = detail.ProcessId.ToString();
                txtQuantity.Text = detail.Quantity;
                txtPrice.Text = detail.Price;
            }
        }
        catch { }
    }

    protected void grid_RowCreated(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                string tax = "";
                if (this.Id > 0)
                {
                    BLLLaundry bll = new BLLLaundry();
                    ReceivedNote r = bll.GetReceivedNoteById(this.Id);
                    tax = r.Tax.ToString().Replace(ConfigurationManager.AppSettings["ThousandSeparator"], ConfigurationManager.AppSettings["DecimalSeparator"]);
                }
                else {
                    BLLSettings bll = new BLLSettings();
                    Setting s = bll.GetSettings();
                    tax = s.Tax.ToString().Replace(ConfigurationManager.AppSettings["ThousandSeparator"], ConfigurationManager.AppSettings["DecimalSeparator"]);
                }
                e.Row.Visible = false;
                //Row Sub Total
                GridViewRow rowFooter = new GridViewRow(0, 0, DataControlRowType.Footer, DataControlRowState.Normal);
                Literal newCells = new Literal();
                newCells.Text = "Sub-Total: &nbsp;";
                TableCell footerTaxCell1 = new TableCell();
                footerTaxCell1.Controls.Add(newCells);
                footerTaxCell1.ColumnSpan = 3;
                footerTaxCell1.CssClass = "totals";
                rowFooter.Cells.Add(footerTaxCell1);
                TextBox total = new TextBox();
                total.CssClass = "detail-input footer-subtotal";
                total.ReadOnly = true;
                TableCell footerTaxCell2 = new TableCell();
                footerTaxCell2.Controls.Add(total);
                rowFooter.Cells.Add(footerTaxCell2);
                rowFooter.Visible = true;
                grid.Controls[0].Controls.AddAt(grid.Controls[0].Controls.Count, rowFooter);
                //Row Tax
                GridViewRow rowFooter1 = new GridViewRow(0, 0, DataControlRowType.Footer, DataControlRowState.Normal);
                newCells = new Literal();
                newCells.Text = "IVA: &nbsp; (%)";
                footerTaxCell1 = new TableCell();
                footerTaxCell1.Controls.Add(newCells);
                footerTaxCell1.ColumnSpan = 3;
                footerTaxCell1.CssClass = "totals";
                rowFooter1.Cells.Add(footerTaxCell1);
                total = new TextBox();
                total.CssClass = "detail-input footer-tax";
                total.ReadOnly = true;
                total.Text = tax;
                footerTaxCell2 = new TableCell();
                footerTaxCell2.Controls.Add(total);
                rowFooter1.Cells.Add(footerTaxCell2);
                rowFooter1.Visible = true;
                grid.Controls[0].Controls.AddAt(grid.Controls[0].Controls.Count, rowFooter1);
                //Row Total
                GridViewRow rowFooter2 = new GridViewRow(0, 0, DataControlRowType.Footer, DataControlRowState.Normal);
                newCells = new Literal();
                newCells.Text = "Total: &nbsp;";
                footerTaxCell1 = new TableCell();
                footerTaxCell1.Controls.Add(newCells);
                footerTaxCell1.ColumnSpan = 3;
                footerTaxCell1.CssClass = "totals";
                rowFooter2.Cells.Add(footerTaxCell1);
                total = new TextBox();
                total.CssClass = "detail-input footer-total";
                total.ReadOnly = true;
                footerTaxCell2 = new TableCell();
                footerTaxCell2.Controls.Add(total);
                rowFooter2.Cells.Add(footerTaxCell2);
                rowFooter2.Visible = true;
                grid.Controls[0].Controls.AddAt(grid.Controls[0].Controls.Count, rowFooter2);
            }
        }
        catch { }
    }
    protected void imgAdd_Click(object sender, ImageClickEventArgs e)
    {
        buildDetails();
        long min = 0;
        try
        {
            min = (from m in details select m.Id).Min();
        }
        catch { }
        if (min > 0)
            min = -1;
        else
            min -= 1;
        BLLProcess DB = new BLLProcess();
        List<Process> processes = DB.GetProcesses();
        BLLLaundry.Full_Detail d = new BLLLaundry.Full_Detail();
        d.Id = min;
        d.Processes = processes;
        details.Add(d);
        bindGrid();
    }
    private void buildDetails()
    {
        for (int i = 1; i <= grid.Rows.Count; i++)
        {
            try
            {
                DropDownList drdProcess = (DropDownList)grid.Rows[i-1].FindControl("drdProcess");
                TextBox txtQuantity = (TextBox)grid.Rows[i-1].FindControl("txtQuantity");
                TextBox txtPrice = (TextBox)grid.Rows[i-1].FindControl("txtPrice");
                HiddenField hdnId = (HiddenField)grid.Rows[i-1].FindControl("hdnId");
                int id = 0;
                int.TryParse(hdnId.Value, out id);
                if (drdProcess.SelectedValue != "" && txtQuantity.Text != "" && txtPrice.Text != "")
                {
                    if (id < 0)
                    {
                        id = id * -1;
                    }
                }
                else
                {
                    id = i * -1;
                }
                long pid = 0;
                long.TryParse(drdProcess.SelectedValue, out pid);
                details[i-1].Id = id;
                details[i-1].Price = txtPrice.Text;
                details[i-1].Quantity = txtQuantity.Text;
                details[i-1].ProcessId = pid;
            }
            catch
            {
            }
        }
    }
    protected bool getEnabled() {
        bool result = true;
        if (this.Id > 0)
        {
            result = false;
        }
        return result;
    }
}